package com.qf.smsplatform.strategy.executor;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.enums.SmsEnum;
import com.qf.smsplatform.common.exception.SmsException;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.client.CacheClient;
import com.qf.smsplatform.strategy.strategy.Strategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * projectName: sms-platform
 *
 * @author: 黄睿武
 * time: 2021/8/13 19:53
 * description: 策略链的执行者,通过执行者指定策略链的执行顺序
 */

@Component
@Slf4j
public class StrategyExecutor {

    /**
     * 需要拿到所有的策略对象
     */
    @Autowired
    private Map<String, Strategy> strategyMap;

    /**
     * 调用缓存模块的feign接口
     */
    @Autowired
    private CacheClient cacheClient;


    public void execute(StandardSubmit submit){
        //1.从其他位置获取到策略对象的执行顺序
        String filters = cacheClient.hget(CacheConstants.CACHE_PREFIX_CLIENT+submit.getClientID(),"filters");

        //2.根据执行顺序,依次执行每个策略的execute方法,并根据执行结果,判断是否需要执行下一步
        if (StringUtils.isEmpty(filters)) {
            log.info("[策略模块---执行策略链]  无法查询当前客户的策略链执行顺序! filters = {}",filters);
            throw new SmsException(SmsEnum.ERROR);
        }
        String[] filterArray = filters.split(",");
        for (String filter : filterArray) {
            //"phase,black,dirtyWord,limitFiveMinutes,limitOneHour,limitOneDay,fee,router"
            Strategy strategy = strategyMap.get(filter);
            if(strategy != null){
                boolean flag = strategy.execute(submit);
                if (!flag) {
                    //凉凉
                    return;
                }
            }

        }

    }
}
